package corn

import (
	"context"
	"strconv"
	"time"
	"yunj/app/enum/articleenum"
	"yunj/app/model"
	"yunj/pkg/baidu"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/core/corn"
	"yunj/pkg/yunj/core/enum/cornenum"
	"yunj/pkg/yunj/util"
)

// 实现TaskInterface接口
type baiduSiteMap struct {
	corn.Task
}

var BaiduSiteMap = func() *baiduSiteMap {
	task := &baiduSiteMap{}
	task.Task.InitTaskInstance(task)
	return task
}()

// 名称
func (t *baiduSiteMap) Name() string {
	return "baidu.site.map"
}

// 描述
func (t *baiduSiteMap) Desc() string {
	return "百度站点收录"
}

// 执行时间
func (t *baiduSiteMap) Spec() string {
	return "0 0 2 * * *"
}

// 超时时间
func (t *baiduSiteMap) Timeout() time.Duration {
	return 10 * time.Second
}

// 定义默认的处理状态（没有配置数据库状态时应用）
func (t *baiduSiteMap) DefaultHandleStatus() uint8 {
	return cornenum.TASK_STATUS_RUNNING
}

// 任务处理函数
func (t *baiduSiteMap) Handler(ctx context.Context) (err error) {
	// 检查是否已取消
	if err = ctx.Err(); err != nil {
		return
	}
	blogUrl := global.Config.App.Url

	// 要收录的地址
	urls := []string{
		blogUrl,
		blogUrl + "/about-us",
		blogUrl + "/category",
	}
	// 所有发布的文章
	var articleIds []int
	global.MySQL.Model(&model.Article{}).Where("status = ? and state = ?", articleenum.STATUS_PUBLISH, stateenum.NORMAL).Pluck("id", &articleIds)
	for _, articleId := range articleIds {
		urls = append(urls, blogUrl+"/article/"+strconv.Itoa(articleId))
	}
	// 因为百度收录推送有限制，所以次数随机获取5条进行推送
	urls = util.RandomSlice(urls, 5)
	// 推送
	baidu.SiteMapSend(urls)
	return
}
